from Pyro.EventService.Clients import Subscriber
import Pyro.util
from threading import Thread

import pynotify, sys

if not pynotify.init("Bluetooth"):
    sys.exit(1)

def Alert(category, *msg):
	print msg
	s = [repr(m) for m in msg]
	n = pynotify.Notification(category, ' '.join(s), '/usr/share/pixmaps/language-selector.png')
	n.set_hint_string('append', '')
	n.show()

class EventListener(Thread, Subscriber):
	def __init__(self):
		Thread.__init__(self)
        	Subscriber.__init__(self)
	def run(self):
		Pyro.core.initServer()
		self.subscribeMatch("^house\\.location.*$")
		print "EVENT LISTENER ACTIVATED", 1
        	self.listen()
    	def event(self,event):
        	# event.msg, subject, time
        	#print "Listener got Event: %s=%s"%(event.subject, event.msg)
		if event.subject == 'house.location.entered':
			Alert('Bluetooth', event.msg, 'has joined.')
		elif event.subject == 'house.location.exited':
			Alert('Bluetooth', event.msg, 'has left.')
		if event.subject == 'house.location.entered.unknow':
			Alert('Bluetooth', 'unknown device detected', event.msg)

class FailureEventListener(Thread, Subscriber):
	def __init__(self):
		Thread.__init__(self)
        	Subscriber.__init__(self)
	def run(self):
		Pyro.core.initServer()
		self.subscribeMatch("^house\\.service.failure.*$")
		print "EVENT LISTENER ACTIVATED", 2
        	self.listen()
    	def event(self,event):
		Alert('Service failure', event.subject, event.msg)

def main():	
	e = EventListener()
	e.start()
	d = FailureEventListener()
	d.start()
	while e.is_alive() or d.is_alive():
		if e.is_alive(): e.join(1)
		if d.is_alive(): d.join(1)

if __name__=="__main__":
	main()
